package com.luoyuanxiangvip.core.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoyuanxiangvip.common.holder.RequestHolder;
import com.luoyuanxiangvip.common.utils.IpUtil;
import com.luoyuanxiangvip.common.vo.BizCommentVO;
import com.luoyuanxiangvip.core.entity.BizComment;
import com.luoyuanxiangvip.core.mapper.BizCommentMapper;
import com.luoyuanxiangvip.core.service.IBizCommentService;
import com.luoyuanxiangvip.core.service.IMailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019-05-30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BizCommentServiceImpl extends ServiceImpl<BizCommentMapper, BizComment> implements IBizCommentService {

    @Resource
    private IMailService iMailService;
    /**
     * 分页
     *
     * @param bizCommentVO page
     * @return page
     */
    @Override
    public IPage<BizComment> findPageBreakByCondition(BizCommentVO bizCommentVO) {
        return this.baseMapper.findPageBreakByCondition(new Page<BizComment>(bizCommentVO.getPage(), bizCommentVO.getLimit()), bizCommentVO);
    }

    /**
     * 评论保存
     *
     * @param comment 评论
     * @return Boolean
     */
    @Override
    public BizComment commentSave(String amapApiAk, BizComment comment) {
        Map<String, Object> map = IpUtil.getIpAndAddress(amapApiAk, RequestHolder.getRequest());
        comment.setStatus(true)
                .setSupport(0)
                .setIp((String) map.get("ip"))
                .setProvince((String) map.get("province"))
                .setCity((String) map.get("city"))
                .setUpdateTime(new Date());
        boolean b = this.save(comment);
        BizComment bizComment = null;
        if(b) {
            bizComment = this.getById(comment.getId());
            this.sendEmail(bizComment);
        }
        return bizComment;
    }

    /**
     * 发送邮件
     * @param comment 评论
     */
    private void sendEmail(BizComment comment){
        // 发送邮件通知，此处如发生异常不应阻塞当前的业务流程
        // 可以进行日志记录等操作
        try {
            iMailService.sendToAdmin(comment);
        } catch (Exception e) {
            log.error("发送评论通知邮件时发生异常", e);
        }
    }
}
